package com.xiguaji.tiktok.v1.ins.product.controller;

import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.config.exception.ParamsException;
import com.xiguaji.tiktok.utils.Ret;
import com.xiguaji.tiktok.v1.InsBaseController;
import com.xiguaji.tiktok.v1.ins.favorite.dto.FavoriteTypeEnum;
import com.xiguaji.tiktok.v1.ins.favorite.model.InsFavorite;
import com.xiguaji.tiktok.v1.ins.favorite.service.InsFavoriteService;
import com.xiguaji.tiktok.v1.ins.product.dto.*;
import com.xiguaji.tiktok.v1.ins.product.service.InsProductService;
import com.xiguaji.tiktok.v1.product.dto.PlatformTypeEnum;
import com.xiguaji.tiktok.v1.product.dto.ReportTypeEnum;
import com.xiguaji.tiktok.v1.tiktok.permission.Limit;
import com.xiguaji.tiktok.v1.tiktok.permission.RequestLimit;
import com.xiguaji.tiktok.v1.user.log.Operation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController("InsProductController")
@Api(value = "ins商品",tags = {"ins商品"})
public class InsProductController extends InsBaseController {

    @Autowired
    InsProductService insProductService;

    @Autowired
    InsFavoriteService insFavoriteService;

    @Autowired
    com.xiguaji.tiktok.v1.product.service.ProductService productPerService;

    @ApiOperation(value = "ins商品列表")
    @RequestMapping(value = "product",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @RequestLimit(value = "ProductPageLimit",property = "page,pageSize",validateType = Limit.VIEW_DATA_LIMIT)
    @Operation(value = "ins商品列表")
    public String getPage(String data) throws UnsupportedEncodingException, ParamsException {
        InsProductSearchRequest insProductSearchRequest = getParam(InsProductSearchRequest.class,URLDecoder.decode(data,"UTF-8"));
        Page<InsProductData> insProductDataPage = insProductService.getPage(insProductSearchRequest);

        insProductDataPage.getList().forEach( productData ->{
            InsFavorite insFavorite = insFavoriteService.getByTypeAndTargetIdAndUserId(FavoriteTypeEnum.INS_PRODUCT.getCode(),productData.getProductId(),(int)getUser().getId());

            if(null != insFavorite) {
                productData.setCollectId(insFavorite.getId());
            }
        });
        return Ret.success("SUCCESS!",insProductDataPage);
    }

    @ApiOperation(value = "搜索ins商品")
    @RequestMapping(value = "product/search",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "搜索INS商品")
    public String searchPage(String data) throws UnsupportedEncodingException, ParamsException {
        InsProductSearchRequest insProductSearchRequest = getParam(InsProductSearchRequest.class,URLDecoder.decode(data,"UTF-8"));

        if(insProductSearchRequest.getPage()*insProductSearchRequest.getPageSize()>10){
            return Ret.noPermission();
        }
        return Ret.success("SUCCESS!",insProductService.getPage(insProductSearchRequest));
    }

    @ApiOperation("ins商品走势")
    @RequestMapping(value = "product/trend/{productId}/{dayType}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "ins商品走势")
    public String product(@PathVariable long productId,@PathVariable int dayType){
        InsProductDetail insProductDetail = new InsProductDetail();
        InsProductStatistics insProductStatistics = insProductService.getProductStatistics(productId,dayType);
        insProductDetail.setInsProductStatistics(insProductStatistics);
        List<InsProductTrend> bloggerTrend = insProductService.getBloggerTrend(productId,dayType);
        List<InsProductTrend> mediaTrend = insProductService.getMediaTrend(productId,dayType);

        for (InsProductTrend m : mediaTrend) {
            for (InsProductTrend b : bloggerTrend) {
                if(m.getTakenDate().equals(b.getTakenDate())){
                    m.setInfluencer(b.getInfluencer());
                }
            }
        }
        insProductDetail.setInsProductTrends(mediaTrend);
        return Ret.success("SUCCESS!",insProductDetail);
    }

    @ApiOperation("ins商品相关帖子")
    @RequestMapping(value = "product/rel/media",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation("ins商品相关帖子")
    public String getProductMedia(String data) throws ParamsException, UnsupportedEncodingException {
        InsProductRelListRequest insProductRelListRequest = getParam(InsProductRelListRequest.class,URLDecoder.decode(data,"UTF-8"));
        return Ret.success("SUCCESS!",insProductService.getProductMediaData(insProductRelListRequest.getProductId(),insProductRelListRequest.getUid(),insProductRelListRequest.getPage(),insProductRelListRequest.getPageSize(),insProductRelListRequest.getMediaType(),insProductRelListRequest.getDayType()));
    }


    @ApiOperation("ins商品相关帖子（时间以当前最新）")
    @RequestMapping(value = "product/rel/media/new",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation("ins商品相关帖子（时间以当前最新）")
    public String getProductNewMedia(String data) throws ParamsException, UnsupportedEncodingException {
        InsProductRelListRequest insProductRelListRequest = getParam(InsProductRelListRequest.class,URLDecoder.decode(data,"UTF-8"));
        return Ret.success("SUCCESS!",insProductService.getProductMediaForNowData(insProductRelListRequest.getProductId(),insProductRelListRequest.getUid(),insProductRelListRequest.getPage(),insProductRelListRequest.getPageSize(),insProductRelListRequest.getMediaType(),insProductRelListRequest.getDayType()));
    }

    @ApiOperation("ins商品相关达人")
    @RequestMapping(value = "product/rel/blogger",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation("ins商品相关达人")
    public String getProductBlogger(String data) throws ParamsException, UnsupportedEncodingException {
        InsProductRelListRequest insProductRelListRequest = getParam(InsProductRelListRequest.class,URLDecoder.decode(data,"UTF-8"));
        return Ret.success("SUCCESS!",insProductService.getProductMediaBlogger(insProductRelListRequest.getProductId(),insProductRelListRequest.getPage(),insProductRelListRequest.getPageSize(),insProductRelListRequest.getDayType()));
    }


    /**
     *
     * @return
     */
    @ApiOperation(value = "验证是否可以解锁报告")
    @RequestMapping(value = "product/report/unlock/checked",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "验证是否可以解锁报告")
    public String checkedUnlockedBloggerReport(String data) throws UnsupportedEncodingException, ParamsException {
        String msg = "";
        Map<String,Object> result = new HashMap<>();
        Integer type = getParam(Integer.class,URLDecoder.decode(data,"UTF-8"),"type");
        // 角色判断
        if(type == 1){
            int roleReportNumber = productPerService.unlockedNumberByRole(getUser().getId(),getRoleId(),ReportTypeEnum.PRODUCT.getMsg());
            if(roleReportNumber <= 0){
                msg = productPerService.userRoleMsg(getRoleId(),ReportTypeEnum.PRODUCT.getMsg());
                result.put("type",1);
            }
            // 报告次数判断
        }else if(type == 2){
            int reportStarterNumber = productPerService.unlockedNumberByReportStarter(getUser().getId());

            if(reportStarterNumber > 0){
                msg += "Your credits reports balance is "+reportStarterNumber+". Unlock this report costs 1 credit. Do you want to continue?";
                result.put("type",2);
            }else {
                //无权限解锁
                result.put("type",3);
            }
        }
        return Ret.success(msg,result);
    }

    /**
     *
     * @param body
     * @return
     * @throws ParamsException
     */
    @ApiOperation(value = "解锁报告")
    @RequestMapping(value = "product/report/unlock",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @Operation(value = "解锁报告")
    public String unlockedBloggerReport(@RequestBody String body) throws ParamsException {
        Long productId = getParam(Long.class,body,"productId");
        if(productPerService.isUnlocked(getUser().getId(),productId, PlatformTypeEnum.INS.getCode())){
            return Ret.success("你已解锁过了");
        }

        if(productPerService.unlockedByUserRole(getUser().getId(),getRoleId(),productId,PlatformTypeEnum.INS.getCode(), ReportTypeEnum.PRODUCT.getCode(), ReportTypeEnum.PRODUCT.getMsg())){
            return Ret.success("解锁成功");
        }

        if(productPerService.unlockedByReportStarter(getUser().getId(),productId, PlatformTypeEnum.INS.getCode(), ReportTypeEnum.PRODUCT.getCode())){
            return Ret.success("解锁成功");
        }
        return Ret.err("解锁失败");
    }


    @ApiOperation(value = "根据帖子查询标记的商品")
    @RequestMapping(value = "product/list/{shortCode}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Operation(value = "根据帖子查询标记的商品")
    public String getProductByMediaShortCode(@PathVariable String shortCode,String data) throws UnsupportedEncodingException, ParamsException {
        InsProductSearchRequest insProductSearchRequest = getParam(InsProductSearchRequest.class,URLDecoder.decode(data,"UTF-8"));
        return Ret.success("SUCCESS",insProductService.getProductByMediaShortCode(shortCode,insProductSearchRequest.getPage(),insProductSearchRequest.getPageSize()));
    }
}
